package com.moarea.app.service.impl.login;

import com.google.gson.Gson;
import com.moarea.app.lang.model.ResultObject;
import com.moarea.app.lang.utils.StringUtils;
import com.moarea.app.model.LoginUser;
import com.moarea.app.resource.ResourceRepository;
import com.moarea.app.service.abst.ABillBaseService;
import com.moarea.app.service.inter.login.ILoginService;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.moarea.app.resource.ResourceRepository.USERNAME;
import static com.moarea.app.resource.ResourceRepository.USERNO;

/**
 * 登录控制接口
 * <p>
 * jizhong
 * <p>
 * 2017-10-26
 */
@Service(value = "loginService")
public class LoginService extends ABillBaseService implements ILoginService {

    /**
     * 用户登录
     * <p>
     * jizhong
     * <p>
     * 2017-10-27
     *
     * @param request 参数
     *                USERNAME 用户名
     *                PASSWORD 密码
     * @param session HttpSession
     */
    @Override
    public ResultObject login(Map<String, String> param, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        //取出用户参数
        String USERNO_P = param.get("username");
        String PASSWORD_P = param.get("password");

        //取出前端参数并处理为接口参数
        Map<String, String> callParamMap = new HashMap<>();
        callParamMap.put(ResourceRepository.USERNO, USERNO_P);
        callParamMap.put(ResourceRepository.PASSWORD, PASSWORD_P);
        callParamMap.put(ResourceRepository.APPNO, APPNO);

        //调用UPMS接口登录
        ResultObject loginResult = callHttpAccess(UPMS_URL + "/api/PublicService/loginToApp",
                new Gson().toJson(callParamMap), "POST");
        if (!loginResult.isSuccess()) {
            return ResultObject.createInstance(false, "网络链接或服务器内部错误");
        }

        //取出访问成功后登录的真实信息
        JSONObject callLoginResult = (JSONObject) loginResult.getData();
        if (!callLoginResult.getBoolean("success")) {
            return ResultObject.createInstance(false, "用户名或密码错误");
        }

        LoginUser loginUser = new LoginUser();

        //登录成功，取出参数
        JSONObject callLoginResultData = callLoginResult.getJSONObject("data");
        String USERNO = callLoginResultData.getString(ResourceRepository.USERNO);
        String USERNAME = callLoginResultData.getString(ResourceRepository.USERNAME);
        String COMPANY_CODE = callLoginResultData.getString(ResourceRepository.COMPANY_CODE);
        String COMPANY_NAME = callLoginResultData.getString(ResourceRepository.COMPANY_NAME);
        String HEADICON = callLoginResultData.containsKey(ResourceRepository.HEADICON) ?
                callLoginResultData.getString(ResourceRepository.HEADICON) : "";
        String GUID = callLoginResultData.getString(ResourceRepository.GUID);
        String IP = getIpAddr(request);

        //存入session
        session.setAttribute(ResourceRepository.APPNO, APPNO);
        session.setAttribute(ResourceRepository.APPNAME, APPNAME);
        session.setAttribute(ResourceRepository.USERNO, USERNO);
        session.setAttribute(ResourceRepository.USERNAME, USERNAME);
        session.setAttribute(ResourceRepository.COMPANY_CODE, COMPANY_CODE);
        session.setAttribute(ResourceRepository.COMPANY_NAME, COMPANY_NAME);
        session.setAttribute(ResourceRepository.HEADICON, HEADICON);
        session.setAttribute(ResourceRepository.GUID, GUID);
        session.setAttribute(ResourceRepository.USER_CLIENT_IP, IP);

        session.setMaxInactiveInterval(10800);


        loginUser.setCOMPANY_CODE(COMPANY_CODE);
        loginUser.setCOMPANY_NAME(COMPANY_NAME);
        loginUser.setUSERNO(USERNO);
        loginUser.setUSERNAME(USERNAME);
        loginUser.setAPPNO(APPNO);
        loginUser.setAPPNAME(APPNAME);
        loginUser.setGUID(GUID);
        loginUser.setHEADICON(HEADICON);
        loginUser.setIP_ADDR(IP);

        session.setAttribute(ResourceRepository.SESSION_LOGIN_USER, loginUser);

        //写入日志
        Cookie cookie = new Cookie(ResourceRepository.USERNO, USERNO);
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);

        cookie = new Cookie(ResourceRepository.USERNAME, StringUtils.escape(USERNAME));
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);

        cookie = new Cookie(ResourceRepository.APPNO, APPNO);
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);

        cookie = new Cookie(ResourceRepository.APPNAME, StringUtils.escape(APPNAME));
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);

        cookie = new Cookie(ResourceRepository.COMPANY_CODE, COMPANY_CODE);
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);

        cookie = new Cookie(ResourceRepository.COMPANY_NAME, StringUtils.escape(COMPANY_NAME));
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);

        cookie = new Cookie(ResourceRepository.HEADICON, HEADICON);
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);

        cookie = new Cookie(ResourceRepository.USER_CLIENT_IP, IP);
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);

        return ResultObject.createInstance(true, "登陆成功");
    }


    /**
     * 获取当前登录用户的信息
     *
     * @param session HttpSession
     * @return 当前登录用户信息
     */
    public ResultObject obtainUserInfo(HttpSession session) {

        Map<String, Object> returnMap = new HashMap<>();

        returnMap.put(USERNO, session.getAttribute(USERNO));
        returnMap.put(USERNAME, session.getAttribute(USERNAME));
        returnMap.put(APPNO, session.getAttribute(APPNO));
        returnMap.put(APPNAME, session.getAttribute(APPNAME));

        return ResultObject.createInstance(true, "", returnMap);

    }


    /**
     * 用户退出
     *
     * @param session HttpSession
     * @return 退出结果
     */
    public ResultObject exit(HttpSession session) {
        session.invalidate();
        return ResultObject.createInstance();
    }

    /**
     * 密码修改
     *
     * @param param   参数
     * @param session HttpSession
     * @return 结果
     */
    @Override
    public ResultObject changePassword(Map<String, Object> param, HttpSession session) {

        param.put("GUID", session.getAttribute(ResourceRepository.GUID));
        param.put("USERNO", session.getAttribute(ResourceRepository.USERNO));

        //调用UPMS接口登录
        ResultObject resultObject = callHttpAccess(UPMS_URL + "/api/PublicService/changePassword",
                new Gson().toJson(param), "POST");
        if (!resultObject.isSuccess()) {
            ResultObject.createInstance(false, "网络链接或服务器内部错误");
        }

        //取出访问成功后登录的真实信息
        JSONObject callResult = (JSONObject) resultObject.getData();

        return ResultObject.createInstance(callResult.getBoolean("success"), callResult.getString("message"));
    }
}
